package com.filter;

import java.io.IOException;  
import java.io.PrintWriter;

import java.util.Enumeration;  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import com.util.Component;


	
	
	public class SqlFilter implements Filter {  
	

		public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
			HttpServletRequest req = (HttpServletRequest) request;  
			HttpServletResponse res = (HttpServletResponse) response;  
			
			req.setCharacterEncoding("utf-8");  //设置request的编码格式
			res.setContentType("text/html;charset=utf-8");
			
			//获得所有请求参数名  
			Enumeration params = req.getParameterNames();  
			String sql = "";  
			while (params.hasMoreElements()) {  
				//得到参数名  
				String name = params.nextElement().toString();  
				//得到参数对应值
				String[] value = req.getParameterValues(name);  
				for (int i = 0; i < value.length; i++) {  
					sql = sql + value[i];  
				}  
			
			}  
			
			//有xss攻击则跳转页面
			if (sqlValidate(sql)) {
				String errs="IP地址"+req.getRemoteAddr()+"发送请求中的参数中含有非法字符,涉嫌恶意攻击！";
				PrintWriter out = response.getWriter();
				out.print(errs);
			} else {  
				chain.doFilter(req, res);
			}  
		}  

		protected static boolean sqlValidate(String str) {  
			str = str.toLowerCase().trim();//统一转为小写  
		
			String badStr = "";  int cout=0;
			badStr = "'|select|update|delete|count|from|insert|and|or|exec|execute|drop|grant|group_concat|" +  
			"information_schema.columns|table_schema|union|where|*|" +  
			"chr|master|truncate|declare|;|--|like|%";//过滤掉的sql关键字，可以手动添加  
			if("".equals(str))return false;
			else{
				String[] badStrs = badStr.split("\\|");
				//System.out.println("验证字符为========="+str);
				for (int i = 0; i < badStrs.length; i++) {  
					
					if (str.indexOf(badStrs[i])>=0) {
						//System.out.println("验证"+cout+"次非法字符为========="+badStrs[i]);
						cout++;
						if(cout>2){
							return true;  
						}
					}  
				}  
				return false;  
			}
		}  
		
		public void destroy() {}  
		public void init(FilterConfig arg0) throws ServletException {}  



	}

